package com.jasmine.bjstkserver.server.article.draft;

import cn.hutool.core.util.StrUtil;
import com.jasmine.auth.util.AuthUtil;
import com.jasmine.bjstkserver.server.article.ArticleConstants;
import com.jasmine.bjstkserver.server.article.draft.model.ArticleDraftEntity;
import com.jasmine.bjstkserver.server.article.draft.model.ArticleDraftRes;
import com.jasmine.bjstkserver.server.article.online.model.ArticleReq;
import com.jasmine.bjstkserver.server.article.log.draftlog.DraftLog;
import com.jasmine.bjstkserver.server.article.log.draftlog.DraftLogEntity;
import com.jasmine.core.dto.R;
import com.jasmine.core.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 文章草稿
 *
 * @author jasmineXz
 */
@RestController
@RequestMapping("/article/draft")
public class ArticleDraftController {

    @Autowired
    private ArticleDraftService articleDraftService;

    /**
     * 草稿列表
     * @param article 文件夹ID等条件
     * @return 草稿列表
     */
    @GetMapping("/list")
    public R findList (@ModelAttribute ArticleReq article){
        article.setUserId(AuthUtil.getUserId());
        return R.ok(articleDraftService.findList(article));
    }


    /**
     * 查询文章内容
     * @param article 查询条件
     *  article#contentType {
     *      ALL  : 显示全部
     *      MD   : 显示markdown内容
     *      HTML : 显示html内容
     *  }
     * @return 文章信息,包含发布文章的点击信息,会与article表联查
     */
    @GetMapping
    public R findOne (@ModelAttribute ArticleReq article){
        article.setUserId(AuthUtil.getUserId());
        return R.ok(articleDraftService.findOne(article));
    }


    /**
     * 新增文章
     * @param article 文章信息
     * @return 文章编号
     */
    @PostMapping
    public R insert (@RequestBody ArticleDraftEntity article) {
        article.setUserId(AuthUtil.getUserId());
        return R.ok(articleDraftService.insert(article));
    }


    /**
     * 修改文章信息,不修改文章内容
     * @param article 文章信息
     * @return 影响行数
     */
    @PutMapping("/info")
    public R updateInfo (@RequestBody ArticleDraftEntity article) {
        article.setUserId(AuthUtil.getUserId());
        // 如果文章ID为空,则新增
        if (null == article.getArticleId()) {
            return this.insert(article);
        }
        return R.ok(articleDraftService.updateInfo(article));
    }


    /**
     * 修改文章内容,不修改文章信息
     * 会记录修改日志
     * @param article 文章信息
     * @return 影响行数
     */
    @DraftLog
    @PutMapping("/content")
    public R updateContent (@RequestBody DraftLogEntity article) throws Exception {
        return R.ok(articleDraftService.updateContent(BeanUtil.copyObject(article,ArticleDraftEntity.class)));
    }


    /**
     * 删除文章,软删除,只修改状态
     * @param article 文章ID
     */
    @DeleteMapping
    public R delete (@RequestBody ArticleDraftEntity article) {
        article.setUserId(AuthUtil.getUserId());
        return R.ok(articleDraftService.delete(article.getArticleId()));
    }


    /**
     * 下载文章,写入文章流
     * @param articleId 文章ID
     */
    @GetMapping("/download")
    public void download (@RequestParam("articleId")Integer articleId, HttpServletResponse response) throws IOException {
        ArticleReq req = new ArticleReq();
        req.setArticleId(articleId);
        req.setContentType(ArticleConstants.CONTENT_MD);
        req.setUserId(AuthUtil.getUserId());
        ArticleDraftRes res = articleDraftService.findOne(req);
        if (StrUtil.isBlank(res.getContentMd())) {
            throw new IllegalArgumentException("文章内容为空,无法下载");
        }

        try (InputStream is = new ByteArrayInputStream(res.getContentMd().getBytes(StandardCharsets.UTF_8));
            BufferedInputStream bis = new BufferedInputStream(is);
            OutputStream os = response.getOutputStream();) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + res.getName() + ".md");// 设置文件名
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }
    }




    /* ------------------- 统计 ------------------- */




    /**
     * 文章统计
     * @param article 用户
     * @return 文章数,字数,点击数,阅读数
     */
    @GetMapping("/statistics/all")
    public R statistics (ArticleReq article) {
        article.setUserId(AuthUtil.getUserId());
        return R.ok(articleDraftService.statistics(article));
    }
}
